package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author :XingJiaCheng
 * @date :2022-40-16-20:40
 * @description
 **/
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(
            HttpServletRequest Request,
            @RequestBody Employee employee) {
        LambdaQueryWrapper<Employee> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee dbEmployee = employeeService.getOne(QueryWrapper);
        if (dbEmployee == null) {
            return R.error("您输入的用户不纯在");
        }
        String dbEmployeePassword = dbEmployee.getPassword();
        String employeePassword = employee.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(employeePassword.getBytes());
        if (!dbEmployeePassword.equals(md5DigestAsHex)) {
            return R.error("您输入的密码不正确");
        }
        Request.getSession().setAttribute("employee", dbEmployee.getId());
        log.info("登录成功");
        return R.success(dbEmployee);


    }
    @PostMapping("logout")
    public R<String>logout(HttpServletRequest request){
        request.getSession().invalidate();
        log.info("消除成功|");
        return R.success("退出成功");


    }


}
